<template>
	<view class="container">
		<!-- 页面顶部 -->
		<view v-if="list.length" class="head-info">
			<view class="cart-edit" @click="handleToggleMode">
				<view v-if="mode == 'normal'" class="normal">
					<text class="icon iconfont icon-bianji"></text>
					<text>管理</text>
				</view>
				<view v-if="mode == 'edit'" class="edit">
					<text>完成</text>
				</view>
			</view>
		</view>


		<!-- 购物车商品列表 -->
		<view v-if="list.length" class="cart-list">
			<l-swipeAction :options="options" :isClickClose="true" @clickItem="clickItem(item.productDetail.id)"
				v-for="(item, index) in list" :key="item">
				<view class="itemContent">
					<view class="radioCotent">
						<label class="item-radio" @click.stop="handleCheckItem(item.productDetail.id)">
							<radio class="radio" color="rgba(196, 143, 82, 1)"
								:checked="inArray(item.productDetail.id, checkedIds)" />
						</label>
					</view>
					<view class="cart-item">
						<view class="goods-image" @click="onTargetGoods(item.productDetail.productId)">
							<image class="image" :src="item.productDetail.productDetailImg" mode="scaleToFill"></image>
						</view>
						<view class="item-content">
							<view class="goods-title" @click="onTargetGoods(item.productDetail.productId)">
								<text class="twoline-hide">{{ item.productName }}</text>
							</view>
							<view class="goods-props clearfix">
								<view class="goods-props-item">
									<text>{{item.productDetail.productDetailSpecifications}}</text>
								</view>
							</view>
							<view class="item-foot">
								<view class="goods-price">
									<text class="unit">￥</text>
									<text class="value">{{ item.productDetail.productDetailPrice }}</text>
								</view>


								<stepper :itemNum="item.shoppingCartQuantity"
									@add="num=>toUpdate(num,item.productDetail.id)"
									@minus="num=>toUpdate(num,item.productDetail.id)"
									@blur="num=>toUpdate(num,item.productDetail.id)">
								</stepper>




							</view>
						</view>
					</view>
				</view>
			</l-swipeAction>
		</view>

		<!-- 购物车数据为空 -->
		<view class="empty" v-if="list===null||list.length===0">
			<view class="iconArea">

			</view>
			<view class="textArea">
				<view class="up">
					购物车空空如也
				</view>
				<view class="down">
					快去逛逛吧
				</view>

			</view>
		</view>
		<!-- 底部操作栏 -->
		<view v-if="list.length" class="footer-fixed">
			<label class="all-radio" @click="handleCheckAll">
				<radio class="radio" color="rgba(196, 143, 82, 1)"
					:checked="checkedIds.length > 0 && checkedIds.length === list.length" />
				<text class="selectAll">全选</text>
			</label>
			<view class="total-info" v-if="mode == 'normal'">
				<text>合计：</text>
				<view class="goods-price">
					<text class="unit">￥</text>
					<text class="value">{{ totalPrice }}</text>
				</view>
			</view>
			<view class="cart-action">
				<view class="btn-wrapper">
					<view v-if="mode == 'normal'" class="btn-item btn-main"
						:class="{ disabled: checkedIds.join() == '' }" @click="handleOrder()">
						<text>去结算</text>
					</view>
					<view v-if="mode == 'edit'" class="btn-item btn-delete" :class="{ disabled: !checkedIds.length }"
						@click="handleDelete()">
						<text>删除</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	// 导入测试数据


	//跟数组操作和优化相关的函数放在util
	import {
		inArray
	} from '@/utils/util'
	//后面就从这个文件里调用后台的增删改接口
	import * as CartApi from '@/api/cart/cart.js'
	import stepper from '@/components/stepper.vue'
	const CartIdsIndex = 'CartIds';
	export default {
		components: {

			stepper
		},
		data() {
			return {
				// #
				list: [],

				inArray,
				// 正在加载
				isLoading: false,
				// 当前模式: normal正常 edit编辑
				mode: 'normal',
				//滑动删除配置
				options: [{
					name: '删除',
					width: 100,
					background: 'red',
					color: '#fff'
				}],

				// 购物车商品总数量

				// 选中的商品ID记录
				checkedIds: [],
				// 选中的商品总金额
				totalPrice: '0.00',
				checkedList: []
			}
		},
		watch: {
			// 监听选中的商品
			checkedIds: {
				handler(val) {
					// 计算合计金额
					this.onCalcTotalPrice()

				},
				immediate: false
			},

		},
		onLoad() {

			this.getCartList();
		},
		onShow() {
			this.resetData()
			this.getCartList();
		},

		methods: {
			// 若没登录出现在个人页应该对数据重置
			resetData() {
				Object.assign(this.$data, this.$options.data.call(this));
			},

			// 获取购物车商品列表
			async getCartList() {
				const res = await CartApi.list();
				this.list = res.data.data;
				this.list = this.list.filter(item => item.productDetail !== null && item.productDetail !== '');
				this.onCalcTotalPrice()
				console.log("购物车列表")
				console.log(res);
				//以下代码是为了判断用户修改购物车子商品属性后是否进行
				// 创建一个空对象用于存储合并后的数据  
				// 创建一个空对象用于存储合并后的数据  
				console.log(this.list)
			},

			//滑动删除事件
			clickItem(id) {
				console.log(id)
				this.deleteOne(id)
				this.getCartList()

			},

			// 计算合计金额 (根据选中的商品)
			onCalcTotalPrice() {
				const app = this
				// 选中的商品记录
				this.checkedList = app.list.filter(item => inArray(item.productDetail.id, app.checkedIds))
				// 计算总金额
				let tempPrice = 0;
				this.checkedList.forEach(item => {
					// 商品单价, 为了方便计算先转换单位为分 (整数)
					const unitPrice = item.productDetail.productDetailPrice * 100
					tempPrice += unitPrice * item.shoppingCartQuantity
				})
				app.totalPrice = (tempPrice / 100).toFixed(2)
			},

			// 切换当前模式
			handleToggleMode() {
				this.mode = this.mode == 'normal' ? 'edit' : 'normal'
			},


			// 跳转商品图片区域根据主产品id跳到商品详情页
			onTargetGoods(goodsId) {
				uni.$toPage('/subpkg/shoppingMall/goods_detail/goods_detail', {
					goods_id: goodsId
				})

			},

			// 点击去逛逛按钮, 跳转到首页
			onTargetIndex() {
				uni.$toPage('/pages/cate/cate');
			},

			// 选中商品
			handleCheckItem(cartId) {
				const {
					checkedIds
				} = this
				const index = checkedIds.findIndex(id => id === cartId)
				index < 0 ? checkedIds.push(cartId) : checkedIds.splice(index, 1)
			},


			// 全选事件
			handleCheckAll() {
				const {
					checkedIds,
					list
				} = this
				this.checkedIds = checkedIds.length === list.length ? [] : list.map(item => item.productDetail.id)
			},

			// 结算选中的商品
			handleOrder() {
				const app = this
				if (app.checkedIds.length) {
					uni.$toPage('/subpkg/shoppingMall/orders_confirm_cart/orders_confirm_cart', {
						toBePurchaseList: this.checkedList
					})
				} else {
					return uni.$showMsg('请选择商品')
				}
			},


			// 删除选中的商品弹窗事件
			handleDelete() {
				const app = this
				if (!app.checkedIds.length) {
					return false
				}

				uni.showModal({
					title: '友情提示',
					content: '您确定要删除该商品吗？',
					showCancel: true,
					success({
						confirm
					}) {

						confirm && app.onClearCart()
					}
				})
				this.getCartList()
			},

			// 确认删除商品
			async onClearCart() {
				// 根据选中的数量调用不同的方法
				if (this.checkedIds.length == 1) {
					this.deleteOne(this.checkedIds[0]);
				} else if (this.checkedIds.length == this.list.length) {
					this.deleteAll();
				} else {
					this.deleteSome()
				}

				//删完后刷新页面数据
				console.log("刷新页面")
				this.getCartList();

			},

			//批量删除（非全删）
			async deleteSome() {
				const res = await CartApi.deleteSome(this.checkedIds);
				this.getCartList()
				// 批量删除
				console.log(res)
			},

			//删除单个
			async deleteOne(id) {
				const res = await CartApi.deleteOne(id);
				this.checkedIds = this.checkedIds.filter(checkedId => checkedId !== id);

				this.getCartList()
			},

			//删除全部
			async deleteAll() {
				const res = await CartApi.deleteAll();
				this.getCartList()
			},

			//进步器的自定义函数
			async toUpdate(num, productDetailId) {
				console.log(num)
				const res = await CartApi.update(productDetailId, num);
				console.log("更新")
				console.log(res)
				if (res.data.code === 200) {
					this.getCartList()
					console.log("增加子商品数量")
				} else if (res.data.code === 320 || res.data.code === 321) {
					this.getCartList();
					return uni.$showMsg('商品信息发生变化')
				}


			},


		}
	}
</script>


<style lang="scss" scoped>
	page {
		background-color: #f3f3f5;
	}

	.container {
		height: 100vh;
		width: 100vw;
		padding: 0;
		margin: 0;
		overflow-y: scroll;

		// 页面顶部
		.head-info {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			padding: 4rpx 30rpx;
			// background-color: #fff;
			height: 100rpx;
			box-sizing: border-box;

			.cart-edit {
				font-size: 28rpx;
				padding-left: 20rpx;
			}

		}

		// 购物车列表
		.cart-list {

			padding: 0 16rpx 110rpx 16rpx;



			.itemContent {

				position: relative;
				box-sizing: border-box;

				display: flex;

				height: 198rpx;
				margin-bottom: 20rpx;


				.radioCotent {
					width: 56rpx;
					height: 80rpx;
					line-height: 80rpx;
					margin-right: 5rpx;
					text-align: center;
					position: relative;

					.item-radio {
						position: absolute;
						right: -12rpx;
						top: 65%;


						.radio {

							transform: scale(0.76)
						}
					}
				}


				.cart-item {

					width: 100%;
					background: #fff;
					display: flex;
					align-items: center;
					padding: 30rpx 16rpx;
					border-radius: 15rpx;



					.goods-image {
						width: 150rpx;
						height: 150rpx;

						.image {
							display: block;
							width: 100%;
							height: 100%;
							border-radius: 8rpx;
						}
					}

					.item-content {
						flex: 1;
						padding-left: 24rpx;

						.goods-title {
							font-size: 28rpx;
							max-height: 76rpx;
						}

						.goods-props {
							margin-top: 14rpx;
							height: 40rpx;
							color: #ababab;
							font-size: 24rpx;
							overflow: hidden;

							.goods-props-item {
								display: inline-block;
								margin-right: 14rpx;
								padding: 4rpx 0rpx;
								border-radius: 12rpx;
								font-size: 28rpx;
								width: auto;
							}
						}


						.item-foot {
							display: flex;
							justify-content: space-between;
							align-items: center;
							margin-top: 20rpx;
							position: relative;

							.goods-price {
								vertical-align: bottom;
								font-size: 36rpx;
								font-weight: 700;
								color: rgba(212, 48, 48, 1);

								.unit {
									font-size: 24rpx;
								}

								.value {
									font-size: 32rpx;
								}
							}


							.stepperContent {
								border: solid;
								position: relative;
								width: 162rpx;
								height: 32rpx;
								box-sizing: border-box;
							}

						}

					}
				}

			}

		}



		// 空数据按钮
		.empty-ipt {
			width: 220rpx;
			margin: 0 auto;
			font-size: 32rpx;
			height: 64rpx;
			line-height: 64rpx;
			text-align: center;
			color: #fff;
			border-radius: 50rpx;
			background: linear-gradient(to right, #f9211c, #ff6335);
		}

		// 底部操作栏
		.footer-fixed {
			display: flex;
			align-items: center;
			height: 96rpx;
			background: #fff;
			padding: 0 30rpx;
			position: fixed;
			bottom: var(--window-bottom);
			left: 0;
			right: 0;
			z-index: 11;

			.all-radio {
				width: 140rpx;
				display: flex;
				align-items: center;

				.selectAll {
					font-size: 30rpx;
					color: #ababab;
				}

				.radio {
					margin-bottom: -4rpx;
					transform: scale(0.76)
				}
			}

			.total-info {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: flex-end;
				padding-right: 30rpx;

				.goods-price {
					vertical-align: bottom;
					color: #fa2209;

					.unit {
						font-size: 20rpx;
					}

					.value {
						font-size: 32rpx;
					}
				}
			}

			.cart-action {
				width: 200rpx;

				.btn-wrapper {
					height: 100%;
					display: flex;
					align-items: center;
				}

				.btn-item {
					flex: 1;
					font-size: 28rpx;
					height: 72rpx;
					line-height: 72rpx;
					text-align: center;
					color: #fff;
					border-radius: 50rpx;
					box-sizing: border-box;
					position: relative;
				}

				// 立即购买按钮
				.btn-main {
					border-radius: 26rpx;
					background: rgba(212, 48, 48, 1);
				}

				//删除状态的按钮样式
				.btn-delete {

					box-sizing: border-box;
					width: 180rpx;
					height: 74rpx;
					opacity: 1;
					border-radius: 27rpx;
					color: rgba(212, 48, 48, 1);
					border: 1rpx solid rgba(0, 0, 0, 1);
					position: absolute;
					top: 16rpx;
					right: 28rpx;

				}

			}


		}


		//空区域
		.empty {
			display: flex;
			flex-direction: column;
			width: 280rpx;
			justify-content: center;
			align-items: center;
			position: absolute;
			left: 236rpx;
			top: 402rpx;

			.iconArea {
				margin-left: 30rpx;
				box-sizing: border-box;
				width: 242rpx;
				height: 124rpx;
				background: url('https://zhinengjiayi.oss-cn-chengdu.aliyuncs.com/mall/spcar_icon_spcar_default%404x.png');
				background-size: cover;

			}

			.textArea {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				font-size: 40rpx;
				font-weight: 400;
				letter-spacing: 0rpx;
				line-height: 57.92rpx;
				color: rgba(102, 102, 102, 1);
				margin-top: 76rpx;



			}

		}

	}

	.container::-webkit-scrollbar {
		display: none;
	}
</style>